package com.example.cinema.controller;

import com.example.cinema.model.Ticket;
import com.example.cinema.service.TicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/tickets")
public class TicketController {

    private final TicketService ticketService;

    @Autowired
    public TicketController(TicketService ticketService) {
        this.ticketService = ticketService;
    }

    // 获取所有已售出的票
    @GetMapping
    public ResponseEntity<List<Ticket>> getAllTickets() {
        List<Ticket> tickets = ticketService.getAllTickets();
        return new ResponseEntity<>(tickets, HttpStatus.OK);
    }

    // 购买电影票
    @PostMapping("/purchase")
    public ResponseEntity<?> purchaseTicket(@RequestBody Map<String, Object> request) {
        try {
            // 从请求中获取参数
            Integer scheduleId = Integer.parseInt(request.get("scheduleId").toString());
            Integer rowNo = Integer.parseInt(request.get("rowNo").toString());
            Integer colNo = Integer.parseInt(request.get("colNo").toString());
            String phone = request.get("phone").toString();

            // 调用服务层购买电影票
            Ticket ticket = ticketService.purchaseTicket(scheduleId, rowNo, colNo, phone);

            // 返回成功响应
            return new ResponseEntity<>(ticket, HttpStatus.CREATED);
        } catch (NumberFormatException e) {
            return new ResponseEntity<>("参数格式错误: " + e.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }
}